package com.c2b.algorithm.leetcode.base;

/**
 * 字符串相加
 *
 * @author c2b
 * @since 2022/5/19 18:17
 */
public class LC0415addStrings {

    public String addStrings(String num1, String num2) {
        // 数组1和数组2的数组下标最大值
        int maxIndexNum1 = num1.length() - 1;
        int maxIndexNum2 = num2.length() - 1;
        StringBuilder builder = new StringBuilder();
        int biggerLength = Math.max(num1.length(), num2.length());
        int val;
        int num;
        int carry = 0;
        for (int i = 0; i < biggerLength; i++) {
            if (i > maxIndexNum1) {
                // num1越界
                val = num2.charAt(maxIndexNum2 - i) - '0' + carry;
            } else if (i > maxIndexNum2) {
                // num2越界
                val = num1.charAt(maxIndexNum1 - i) - '0' + carry;
            } else {
                // 都不越界
                val = num1.charAt(maxIndexNum1 - i) - '0' + num2.charAt(maxIndexNum2 - i) - '0' + carry;
            }
            carry = val / 10;
            num = val % 10;
            builder.append(num);
        }
        if (carry >= 1) {
            builder.append(carry);
        }
        return builder.reverse().toString();
    }

    public static void main(String[] args) {

    }
}
